#  创建会话, 创建与删除所有表, 初始化数据
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from .setting import settings
from common.custom_log import my_logger

from table.base import Base
from table.user import User
from table.role import Role
from table.user_role import UserRole
from table.group import Group

# 创建表引擎
engine = create_engine(
    url=settings.DATABASE_URI,  # 数据库uri
    echo=settings.DATABASE_ECHO,  # 是否打印日志
    pool_pre_ping=True,  # 每次连接前都会检查连接是否有效
)

# 会话创建器
SessionLocal = sessionmaker(autocommit=False, expire_on_commit=False, autoflush=True, bind=engine)


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def init_table(is_drop: bool = True):
    my_logger.info("DATAbASE...")
    """ 创建 database 下的所有表 """
    if is_drop:
        drop_table()
    try:
        my_logger.info("初始化数据库连接...")
        Base.metadata.create_all(bind=engine)
        my_logger.info("数据库连接成功!!!")
    except Exception as e:
        my_logger.error(f"数据库连接失败!!! -- 错误信息如下:\n{e}")


def drop_table():
    """ 删除 database 下的所有表 """
    try:
        Base.metadata.drop_all(bind=engine)
        my_logger.info("删除表成功!!!")
    except Exception as e:
        my_logger.error(f"删除表失败!!! -- 错误信息如下:\n{e}")


def init_data():
    """ 初始化表数据 """
    with SessionLocal() as session:
        # 密码123456
        user1 = User(name="admin", password="$2b$12$hFDWPKRuMvWn8TIxBKmcJuh5QRb/vyrmsCi9.ajYyxZmcJ7/.zdcW")
        user2 = User(name="user", password="$2b$12$hFDWPKRuMvWn8TIxBKmcJuh5QRb/vyrmsCi9.ajYyxZmcJ7/.zdcW", sex=1)
        user3 = User(name="guest", password="$2b$12$hFDWPKRuMvWn8TIxBKmcJuh5QRb/vyrmsCi9.ajYyxZmcJ7/.zdcW", sex=2)
        role1 = Role(name="超级管理员", code="ROLE_ADMIN", description="管理员", updata_by_user_id=1)
        role2 = Role(name="管理员", code="ROLE_USER", description="普通用户", updata_by_user_id=1)
        role3 = Role(name="游客", code="ROLE_GUEST", description="普通用户", updata_by_user_id=1)

        user_role1 = UserRole(user_id=1, role_id=1)
        user_role2 = UserRole(user_id=2, role_id=2)
        user_role3 = UserRole(user_id=3, role_id=3)

        group1 = Group(ancestors='0', dept_name='根组织', leader='张明')

        session.add_all([
            user1, user2, user3,
            role1, role2, role3,
            user_role1, user_role2, user_role3,
            group1
        ])

        session.commit()
